import atexit
import os
import signal
import sys

from flask import Flask, request
from flask_cors import CORS
from werkzeug.serving import is_running_from_reloader

from configs.global_config import global_config
from configs.swagger_config import SwaggerConfig
from controllers import register_controllers
from minio_modules.minio_client import MinioClient, MinioConfig
from nacos_modules.nacos_manager import NacosManager
from utils.logger_config import logger
from utils.path_utils import PathUtils

# 导出声明
__all__ = ['app', 'cors']


# 解析命令行参数
# parser = argparse.ArgumentParser(description="媒体信息处理服务")
# parser.add_argument("--config", type=str, help="配置文件路径")
# args = parser.parse_args()

# 初始化全局配置
global_config.initialize()

# 打印系统信息
logger.info(f"操作系统: {PathUtils.get_platform()}")
logger.info(f"项目根目录: {PathUtils.get_project_root()}")
logger.info(f"当前工作目录: {os.getcwd()}")
logger.info(f"Python路径: {sys.path}")

# 创建Flask应用
app = Flask(__name__)

# 从全局配置中读取CORS配置
# 获取CORS origins列表
cors_origins = global_config.get("cors.origins", ["*"])
logger.info(f"CORS origins: {cors_origins}")

# 为所有路由启用CORS，允许来自指定域名的请求
app.config['CORS_ORIGINS'] = cors_origins
cors = CORS(app, resources={r"/*": {"origins": cors_origins}})

# 监听地址
LISTEN_HOST = global_config.get("service.listen_host", "0.0.0.0")
# 服务端口
PORT = global_config.get("service.port", 5555)
# 调试模式
DEBUG = global_config.get("service.debug", False)

# 初始化Nacos管理器
nacos_manager = NacosManager(global_config.raw_config)

# 初始化MinIO客户端
minio_config_dict = global_config.raw_config.get_minio_config()
minio_config = MinioConfig(
    endpoint=minio_config_dict.get("endpoint"),
    access_key=minio_config_dict.get("access_key"),
    secret_key=minio_config_dict.get("secret_key"),
    secure=minio_config_dict.get("secure"),
    bucket=minio_config_dict.get("bucket"),
    public_url=minio_config_dict.get("public_url"),
)
minio_client = MinioClient(minio_config)

# 将MinIO客户端添加到应用配置中
# app.config["MINIO_CLIENT"] = minio_client
app.minio_client = minio_client

# 检查MinIO客户端是否可用
if minio_client.is_available():
    logger.info(f"MinIO客户端初始化成功，存储桶: {minio_config.bucket}")
else:
    logger.warning("MinIO客户端初始化失败，部分功能可能不可用")


# 注册服务到Nacos
def register_to_nacos():
    nacos_manager.register()


# 从Nacos注销服务
def deregister_from_nacos():
    nacos_manager.deregister()


# 注册退出处理函数
atexit.register(deregister_from_nacos)


# 处理信号
def signal_handler(sig, frame):
    logger.info("接收到终止信号，正在关闭服务...")
    deregister_from_nacos()
    # 确保服务器套接字被正确关闭
    try:
        if (
            hasattr(request, "environ")
            and "werkzeug.server.shutdown" in request.environ
        ):
            request.environ["werkzeug.server.shutdown"]()
    except RuntimeError:
        # 当不在请求上下文中时忽略错误
        pass
    sys.exit(0)


if not is_running_from_reloader():
    # 确保在非重载模式下才注册信号处理
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

# 注册所有控制器
controllers = register_controllers(app)

# 使用SwaggerConfig类初始化Swagger - 移到控制器注册之后
swagger_config = SwaggerConfig(
    title="媒体信息处理服务API文档",
    description="提供人脸特征提取、语音识别等功能的API",
    version="1.0.0",
    contact_name="API Support",
    contact_email="support@example.com",
    ui_version="3.x",  # 可以切换为 "2.x" 使用老式UI
)

# 初始化Swagger
swagger = swagger_config.init_swagger(app)

@app.before_request
def check_cors():
    """动态检查CORS配置"""
    if 'CORS_ORIGINS' in app.config:
        origin = request.headers.get('Origin')
        if origin and origin not in app.config['CORS_ORIGINS'] and app.config['CORS_ORIGINS'] != ["*"]:
            from utils.api_response_utils import create_error_response
            return create_error_response(403, "Origin not allowed")

# 主程序入口
if __name__ == "__main__":
    # 注册到Nacos
    register_to_nacos()

    # 启动Flask应用
    try:
        logger.info(f"正在启动服务{LISTEN_HOST}，端口: {PORT}")
        app.run(host=LISTEN_HOST, port=PORT, debug=DEBUG, threaded=True)
    except Exception as e:
        logger.error(f"服务启动失败: {str(e)}")
        deregister_from_nacos()
